import sys,time
from qasync import QEventLoop, asyncSlot
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QPushButton
import asyncio

class MainWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.layout = QVBoxLayout()
        
        self.button = QPushButton("运行协程1")
        self.button.clicked.connect(lambda: self.run_coroutine(1))
        self.layout.addWidget(self.button)
        
        self.button2 = QPushButton("运行协程2")  # 新增按钮
        self.button2.clicked.connect(lambda: self.run_coroutine(2))  # 连接点击事件
        self.layout.addWidget(self.button2)  # 添加到布局
        
        self.setLayout(self.layout)

    @asyncSlot()
    async def run_coroutine(self,i):
        #await asyncio.sleep(2)  # 模拟异步操作
        while True:
            await asyncio.sleep(1)  # 模拟异步操作
            print("协程：",i,time.strftime("%Y-%m-%d %H:%M:%S"))

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.setWindowTitle("异步操作示例")
    window.resize(300, 200)
    window.show()

    # 创建 asyncio 事件循环并绑定到 Qt
    loop = QEventLoop(app)
    asyncio.set_event_loop(loop)

    sys.exit(app.exec())